home *** CD-ROM | disk | FTP | other *** search
/ Mac Cube 4: Multimedia Applications / MacCube Volume 4: Multimedia Applications.iso / Graphics / Sparkle241 folder / (Docs) / Technical notes < prev   
Text File  |  1994-11-30  |  31KB  |  610 lines

  1. Contents:
  2. ABOUT MPEG
  3. ABOUT CONVERSION TO QUICKTIME
  4. MISC SIZE AND TIMING NOTES
  5. ABOUT THE THREAD USAGE
  6. ABOUT THE RESOURCES.
  7. TIMING FOR WAITNEXTEVENT() AND FRIENDS
  8. ACCURATE TIMINGS FOR SPARKLE.
  9. ABOUT THE MPEG ENCODING ALGORITHMS
  10.  
  11. This file contains various pieces of informationa about MPEG and Sparkle. 
  12. Parts of it are notes I take for myself as I alter and test the program.
  13. I included them here because I thought some other mac programmers out there
  14. might be interested in such things. Read through what you care about and 
  15. understand and ignore the rest.
  16.  
  17.  
  18. -------------------------------------------------------------------------------
  19. ABOUT MPEG
  20.  
  21. MPEG is an international standard for video compression. It compresses 
  22. frames at two levels. Firstly frames are compressed internally, and 
  23. secondly frame differences are compressed rather than transmitting full 
  24. frames. 
  25. To understand MPEG one should first understand JPEG. MPEG uses the same 
  26. ideas as JPEG for much of its compression, and suffers from the same 
  27. limitations. 
  28. JPEG compression begins by changing an image's color space from RGB 
  29. planes to YUV planes, where Y is the luminance (brightness of the image) 
  30. and U and V store color information about the image. Half the color 
  31. resolution in the horizontal and vertical planes is dropped, because the 
  32. eye is less sensitive to color than to brightness. These YUV planes are 
  33. then divided into 8 by 8 blocks of pixels. The 64 coefficients in this 8 
  34. by 8 block are fourier transformed concentrating the energy of the image 
  35. in a few coefficients at low frequencies. The high frequency terms of the 
  36. fourier transform can be discarded as the eye is not sensitive to them. 
  37. The resultant fourier transform coefficients are then encoded using a 
  38. variable length coding scheme (basically Huffman coding) so that 
  39. frequently occuring patterns of coefficients are transmitted in few bits 
  40. and rare patterns transmitted in many bits.
  41.  
  42. MPEG goes beyond this by adding support for inter-frame compression. This 
  43. compression works by realizing that most video consists of foreground 
  44. objects moving over a largely static background. Thus rather than 
  45. transmit the foreground and background pictures over and over again, what 
  46. is transmitted is the motion of the foreground objects. Note that this is 
  47. different from the way QuickTime does interframe compression. What 
  48. QuickTime does is just to subtract the two images from each other and 
  49. compress the resultant image (which is hopefully largely blank space.)
  50. The MPEG scheme gives much better compression, but is much harder to 
  51. program. It is essentially a pattern recognition problem, looking at a 
  52. set of frames and deciding what pixels in the frame correspond to moving 
  53. objects---the sort of thing humans are very good at and computers very 
  54. bad at. For this reason, a complete MPEG compressor is complex and very 
  55. slow.
  56.  
  57. MPEG movies consist of three types of frames. I-frames are like JPEG 
  58. images and are compressed by themselves. P-frames are compressed based on 
  59. motion relative to a previous frame. B-frames are compressed based on 
  60. motion relative to both a previous frame AND a future frame. How do you 
  61. know what the future frame is? Well the MPEG data is not stored in the 
  62. same order as it is displayed. You have to decode future frames before 
  63. the B-frames on which they depend, then buffer the future frame 
  64. somewhere. This is why MPEG players need rather more memory than 
  65. QuickTime players.
  66.  
  67. As an example, here's a comment from my code.
  68. //About these three counters:
  69. //DecodedFrameNumber tells where we are in the file which we are currently
  70. //parsing, and is needed to find one's way around this file. It is incremented
  71. //every time a new frame is parsed.
  72. //DisplayedFrameNumber gives the number in temporal sequence of the frame that
  73. //is currently being shown on the screen. 
  74. //For I and P MPEGs these are the same,    but not for B MPEGs. For example a 
  75. //B MPEG may have the sequence:
  76. //    0    1    2    3    4    5    6    7    8    9    10    decodedFrameNumber
  77. //    I    P    B    B    I    B    B    P    B    B    I    frameType
  78. //    0     3    1    2 !    2    0    1    5    3    4 !    2    display number (within group)
  79. //     --------------|-----------------------|---- group boundaries
  80. //    1    4    2    3    7    5    6    10    8    9    ?    displayedFrameNumber
  81. //Note how the frames are clustered in groups, within which the Pict structure's
  82. //temporalReference field give the display number within that group. 
  83. //The displayedFrameNumber is basically a sum of these as one passes from group
  84. //to group, along with a condition of starting at one, rather than zero.
  85. //Now consider random access:
  86. //If we want to make a random access jump to a frame around displayed frame 5, 
  87. //we will be vectored to decodedFrameNumber 4, which will then be decoded, 
  88. //skipping past decodedFrameNumbers 5 and 6 (which depend on another frame in 
  89. //addition to decodedFrameNumber 4, and hence can't be displayed) to finally 
  90. //arrive at displaying decodedFrameNumber 4 as displayedFrameNumber 7. 
  91. //the variable decodedFrameNumberOfVisibleFrame keeps track of this fact that 
  92. //the displayedFrameNumber 7 actually represents decodedFrameNumber 4.
  93. //This information is necessary when stepping backwards through an MPEG. 
  94. //If we are at displayedFrameNumber 7 and step back, we will look back for I-frames
  95. //until we get to the I-frame at decodedFrameNumber==4. But this is the I-frame of
  96. //the image we are just displaying, so we actually need to then step back to an 
  97. //earlier I-frame. 
  98. //This complication is all necessary partially because of the way MPEG forward 
  99. //coding works, with the frame sequence on file not corresponding to the viewed
  100. //sequence, also partially because some B MPEGs do not have valid data for 
  101. //their Pict.temporalReference fields, thus one cannot rely on that field to be 
  102. //valid but one has to maintain a state machine as one parses through the file.
  103.  
  104. An MPEG movie can consist of only I-frames. This will be far from 
  105. optimally compressed, but is much easier to encode because the pattern 
  106. recognition is not needed. Such a movie is pretty much what you would get 
  107. if you made a QuickTime movie and used the JPEG codec as the compression 
  108. option. Because the I-frame movie is so much easier to calculate, it is 
  109. much more common. Sparkle checks if a movie uses only I-frames and if so 
  110. reduces its memory requirements since such movies do not need complex 
  111. buffering. In the PC world, many people talk about XING type MPEGs which 
  112. are pure I-frame MPEGs. These are produced by XING hardware on PCs and 
  113. played back using the XING MPEG player.
  114.  
  115. One problem with the MPEG standard is that many vendors seem to feel 
  116. which parts of it they support are optional. XING, for example, often 
  117. does not ends its MPEGs properly. It does not start frame numbering 
  118. properly, and does not correct frame numbering after MPEGs are edited.
  119. GC technologies produces MPEGs that have the frames essentially random 
  120. numbered, and has garbage frames at the start of its MPEGs.
  121. Wherever possible I have tried to adapt my code to common pathologies in 
  122. MPEG encoders. 
  123. I have also built in powerful yet computationally cheap 
  124. error-detection and recovery. For example a recent MPEG posted to usenet 
  125. drew widespread complaints because some of the uuencoded text was garbled 
  126. and the resultant MPEG crashed pretty much every decoder out there. But 
  127. Sparkle noticed the error and went on quite happily. Sparkle has also 
  128. proved quite robust in the face of MPEGs I have deliberately corrupted.
  129. If you come across any MPEG file that causes Sparkle to crash or produce 
  130. garbage, I WANT TO KNOW ABOUT IT. With a copy of the file, I can trace 
  131. through Sparkle, find just what causes the crash, and make Sparkle even 
  132. more robust.
  133.  
  134. For more details on MPEG, read the MPEG FAQ on USENET. It is posted once 
  135. a week to the picture groups and to news.answers.
  136.  
  137. ------------------------------------------------------------------------------
  138. ABOUT CONVERSION TO QUICKTIME
  139.  
  140. The following are notes I've made on conversion to QuickTime. I have  
  141. investigated this issue extensively, but not exhaustively. If someone has 
  142. comments on the subject---more extensive notes than I have, corrections, 
  143. whatever, please tell me.
  144.  
  145. All times I give are on my SE/30 with a 32-bit screen. People should 
  146. extrapolate to their machines---I guess LC IIs are about half as 
  147. fast and Centris/Quadras three to six times as fast.
  148.  
  149. The useful codecs are video, cinepak (used to be compact video) and jpeg. 
  150. JPEG compression at normal quality gives files of very good quality and not 
  151. much larger than pure I-frame MPEGs. A 120x160 image can play back at about 
  152. 4fps. Translated to an 040 and you get a useful frame rate. However JPEG 
  153. has a major problem in that when it decodes to a 32bit screen, it draws 
  154. directly to the screen, not to an offscreen Gworld unlike other codecs. 
  155. This produces movies with obvious tearing artifacts. When fast-dithering is 
  156. used to draw to other screen depths, it works fine. I don't understand why 
  157. this problem with 32 bit screens should be the case, but I have told Apple 
  158. about this problem and maybe it'll be fixed in a later release of 
  159. QuickTime. Meanwhile write to Apple and complain---they are holding back a 
  160. useful capability. 
  161.  
  162. With the video and cinepak compressors, it is very important to check the 
  163. key-frame rate checkbox. Key-frames are like MPEG I-frames. They are 
  164. compresed standalone and do not depend on other frames. The other frames 
  165. produced by the movie codecs depend on previous frames. Setting the 
  166. key-frame rate guarantees that at least that rate of key-frames (one 
  167. frame in used. for example) will be used. Checking the key-frame rate 
  168. checkbox allows the movie to use intra-frame compression (ie not just 
  169. key-frames) and gives movies half as small as they would otherwise be.
  170. The lower you set the key frame rate to (this means a larger number in 
  171. the QuickTime saving options dialog box) , the smaller you movie will be.
  172. For example a 72K MPEG (48 frames, 120x160, pure I-frame) became a 290K 
  173. movie without keyframes, a 160K movie with a key-frame rate of 1 in 8, 
  174. and a 138K movie with a key-frame rate of 1 in 96. 
  175. The price you pay for a low key-frame rate is that the movie has more 
  176. difficulty when playing backwards, or when randomly jumping around. I 
  177. don't find it a problem and usually use a key-frame rate of about 1 in 
  178. 100, but try for yourself to see what things are like.
  179. Video gives better quality results when a higher key-frame rate is used.
  180. Strangely cinepak appeared to give lower quality results (as well as a 
  181. larger movie) when more key-frame were used. 
  182. I'll have to investigate this further---I may have become confused when I 
  183. was making the measurements. Anyone want to confirm or deny this?
  184. (For comparison, this same movie became a 90K JPEG movie.)
  185.  
  186. I find video and cinepak give much the same file sizes at the same 
  187. (around normal) quality setting. The cinepak file is consistently a 
  188. little larger, but not enough to matter. The video file is consistently 
  189. lower quality for the same size as the cinepak file. However the video 
  190. low quality artifacts (blocks of solid color) I find less psychologically 
  191. irritating than the cinepak low quality artifacts (general fuzzing of 
  192. borders like everything is drawn in crayon and watercolor). 
  193. However cinepak has the advantage of playing back much faster than video. 
  194. For a 120x160 image on my 32bit screen, I can get smooth playback with 
  195. cinepak at 24fps. Video can do smooth playback up to about 16 fps.
  196.  
  197. Fast dithering seems to be a good job for speed (at the cost of quality). 
  198. Unlike earlier versions of QuickTime, with 1.6.1 I found the same speed 
  199. of playback (ie same degree of skipping frames or not) at every screen 
  200. depth but 2 bit depth.
  201.  
  202. Cinepak can support a largish MPEG to QuickTime movie (352x240) at 6fps 
  203. on my mac, but no faster.
  204.  
  205. Compression using cinepak is SLOW SLOW SLOW. A 120x160 frame takes about 
  206. 10 seconds to compress. A 352x240 frame takes about a minute. In this 
  207. time your mac is stuck---it looks like it has crashed. Don't start saving 
  208. to cinepak QuickTime unless you are prepared to walk away from your mac 
  209. and not touch it until it's done.
  210. QuickTime 1.5 did not include anyway to do this compression in small 
  211. chunks so that it would run nicely in the background. I received word 
  212. today that QuickTime 1.6 does have this capability, so once I get the 
  213. relevant techincal documents and read them, I will add this ability.
  214.  
  215. See the WHY DOESN"T SPARKLE DO... section for more information about MPEG 
  216. frame rates and their relationship to QuickTime frame rates.
  217.  
  218. ================================================================================
  219.  
  220. MISC SIZE AND TIMING NOTES
  221.  
  222. These are rough notes I take as I alter the code, partially out of interest 
  223. and partially to guide me in where I need to change things.
  224. They may be of interest to some of you.
  225. They are timed on my new Q610  The timings may not be be consistent with 
  226. each other as they reflect the state of the code at different times. In 
  227. between I may change the code quite a bit---mainly of interest are the 
  228. differences within any group of results.
  229.  
  230. Timings for Erika1.MPG under Sparkle 2.0 on my Q610.
  231. This is a 41 frame pure I 120x160 frame MPEG.
  232.  
  233. These times are for a version of the code that does not call WNE while playing:
  234.  
  235. 1) Effect of the screen depth/dithering on times: (non-optimized code)
  236.     24-bit color:      8.2 s
  237.     16-bit color     9.2 s
  238.      8-bit color      10.1 s
  239.      8-bit grey         8.6 s
  240.      Conclusion:
  241.          probably worth adding hints to speed up some parts of the code to compensate
  242.          for the dithering times:
  243.          1) For  8 bit color use 4x4 IDCT.
  244.          2) For  8 bit grey, omit YUV->RGB conversion.
  245.          3) For 16 bit color, use a special YUV->RGB conversion.
  246.          
  247. 2) Effect of various TC6 optmizations:     (24-bit screen)
  248.     Defer and combine stack adjusts:        7.8 s
  249.     Suppress redundant loads:                7.7 s
  250.     Automatic register assignment:            7.6 s
  251.     Global:    
  252.         Induction variables:                7.4 s
  253.         Common sub-expression elimination:    7.3 s
  254.         Code motion:                        7.2 s
  255.         Register coloring:                    6.6 s
  256.  
  257. 3) Effects of various displayings:    (no optimizations)
  258.     No progress proc at all (implies NOTHING ever updated on screen):    6.7 s
  259.     Progress proc called but does nothing:                                6.8 s
  260.     Progress proc updates movie controller/text track only:                7.6 s
  261.     Progress proc updates only MPEG frames, not movie controller        7.3 s
  262.     Progress proc updates both:                                            8.1 s
  263.     Conclusion:
  264.         of the 8.1 s, 0.8 s=10% is used updating movie controller and
  265.                       0.5 s= 6% is used updating the MPEG frames.
  266.  
  267. 4) Effect of the time allowed a thread before it yields:
  268.     Yield time=6000 ticks (ie never yield)        8.0 s
  269.                 180 ticks                         8.1 s
  270.                  60 ticks                        8.2 s
  271.                  20 ticks                        8.6 s
  272.     One would rather have a 20 tick time than a 60 tick time for increased 
  273.     user interactivity, but the time cost is rather stiff.
  274.     However by implementing a new thread scheduler, I should be able to reduce
  275.     this cost somewhat.
  276.  
  277. 5) Effect of yield time in the background:
  278.     We convert Erika1.MooV to an I-frame MPG.
  279.     FG time (yield time of 30 ticks): 1min 12s
  280.     BG time (yield time of 10 ticks)  2min 30s
  281.     BG time (yield time of 30 ticks)  2min 04s
  282.     Conclusion:
  283.         The longer yield time is obviously better but makes things more choppy.
  284.         Best is probably to implement a timer keeping track of how fast we are 
  285.         getting background NULLs and increasing bgYieldTicks as we notice less
  286.         fg activity.
  287.  
  288. 6) Note: 
  289.     I have tried to put yield brackets around all the hotpoints of the code to 
  290.     make it run well in background. The main problem for now, that I need to work 
  291.     around (ProgressProcs ?) is when the new frame is requested for coding an MPEG
  292.     or QT movie from a QT document. The fiddling that goes on to obtain this frame
  293.     can be fairly substantial, taking as long as 70 or 80 ticks for a simple 
  294.     160x120 movie. My guess is that QT doesn't do very smart caching about 
  295.     non-synch frames and has to decompress a long sequence to get to these frames.
  296.     Anyways, because of this we're stuck with a basic jerkiness at that 
  297.     granularity for now.
  298.  
  299. 7) Effects of four different P algorithms.
  300.     We convert Erika1.MooV to four MPEGs, all using a PPPI pattern,
  301.     with an I-quantization of 8 and a P-quantization of 10.
  302.     Algorithm:                Time:            Size:
  303.     Logarithmic                1:45 min        53 953
  304.     Two level                2:45 min        54 328
  305.     Subsample                3:45 min        54 765
  306.     Exhaustive                5:55 min        54 677
  307.     There was no obvious difference in quality between these MPEGs (and they 
  308.     were all pretty lousy). Thus there seems no real advantage to using anything
  309.     but the fastest algorithm.
  310.  
  311. 8) Effects of P-quantization.
  312.     Evene with a P-quantization of 8, the above setup does not produce as good 
  313.     an image as a pure I sequence (although the file size of 62K is much smaller.)
  314.     This appears to be largely due to the successive dependencies caused by 
  315.     the three successive P frames. 
  316.     Is it better to reduce the number of Ps or lower the P-quantization?
  317.     Using same pattern but P-quantization of 4 gives a file size of 98K and 
  318.     a quality lower than the pure I-frames (though certainly better than what 
  319.     we had). Using a pattern of PPI and P-quantization of 8 gives a file size of 
  320.     71K and the same sort of quality.
  321.     
  322.     Using a PBBIBB pattern and all quantizations as 8 gives a size of 60K and 
  323.     the same sort of quality. 
  324.     
  325.     Conclusions:
  326.     1) I need to use a higher quality source of images to investigate these 
  327.     affects. 
  328.     2) I think the P and B pattern matching criteria may be a bit dodgy, or maybe
  329.     some part of my code has problems with half-pixels or such.
  330.  
  331. 9) Effect of buffer size.
  332.     I played a 750K MPEG of 150 frames. With a buffer size of two frames, it took
  333.     36s. With a buffer size of 200 frames (ie entire movie) it took 33s. Thus
  334.     the larger buffer buys about 10% speed. 
  335.     So maybe, when time, create massive buffers which are in some way shrinkable.
  336. ----------------------------------------------------------------------------------
  337.  
  338. Sizings for Erika1.MPG under Sparkle 2.0
  339.  
  340. 1) Using only I-frame encoding with varying I-quantization:
  341.     I-quantization            size in bytes
  342.             1                    237 307
  343.             2                    179 960
  344.             4                    132 916
  345.             8                     92 210
  346.            16                     66 821
  347.            24                     42 658
  348. //These two values are bogus, now that I've cleaned up the MPEG generating 
  349. //code.
  350. //           32                      37 094
  351. //           64                    25 955
  352.     DC terms only                 21 695
  353.     
  354.     Notes:
  355.     • These sizes are probably slightly larger than necessary as at present I do not
  356.       pad the excess pixels where frame size is smaller than the frame size in 
  357.       macroblocks, thus the DCT is encoding crud at those borders. By padding those 
  358.       to DC we'll get a small shrinkage in size.
  359.     ! This was fixed in version 2.01. The shrinkage was way more than I 
  360.       expected, of the order of 15%.
  361.     • With this set of images (which were pretty lousy to begin with) a quantization 
  362.       level of 8 produced acceptable images, while a level of 16 produced 
  363.       unnacceptable quality.
  364. ================================================================================
  365.  
  366. ABOUT THE THREAD USAGE
  367.  
  368. I have nothing special to say about using threads except that I recommend 
  369. all serious Mac coders read the Apple documentation and use them. They 
  370. make life so much easier. The 1.x code was full of the most ghastly and 
  371. convoluted logic to enable breaking out of the MPEG decoder into the main 
  372. event loop and back again. However the 2.x code for encoding is ridiculously
  373. simple. We simply have the encoder, written (like a UNIX process or such) 
  374. as on long loop, then in the loop at appropriate points we make Yield() 
  375. calls.
  376.  
  377. The one thing that one has to be careful of is using exception handling in 
  378. the TCL. Because this is based on application wide globals, dreadful 
  379. things can happen in your thread when an exception occurs, a string of 
  380. CATCH handlers is followed up the stack, and at some point you leave the 
  381. stack of the thread and enter the "stack of the application". My solution 
  382. to this was to use custom thread context switchers which, on every context 
  383. switch, swap the appropriate exception handling globals.
  384. The custom context switchers also become a good place for updating the 
  385. timings of each thread and setting when it will next yield.
  386.  
  387. At present I'm only using cooperative threads. It's not clear to me that 
  388. switching to pre-emptive threads is a useful excercise. One problem is, of 
  389. course, that pre-emptive threads make life rather trickier and coding more 
  390. complex. More to the point, pre-emptive threads only get half the CPU 
  391. time, while the WaitNextEvent() loop gets the other half. So by switching 
  392. to them I'd get lose half my speed, and not gain much. I might gain 
  393. slightly smoother user event support, especially in the background, but 
  394. that's not that bad right now and will improve when I install a custom 
  395. thread scheduler in place of the hokey quick kludge I'm using right now.
  396. If anyone out there has worked with pre-emptive threads and has opinions 
  397. on them one way or the other, please let me know.
  398.  
  399. A second major change in the 2.x code is I have now structured things 
  400. around a model of video source objects and video encoder objects, with any 
  401. video source able to be linked to any video encoder.
  402. This makes for very orthogonal extensible code.
  403. The natural extension of this is now to define more video sources. In 
  404. particular as soon as I can I hope to get to work on morphing routines, 
  405. with output that can be played to screen or saved in whatever video 
  406. formats I'm supporting by that stage. I have some ideas for morphing 
  407. algorithms, but if anyone can send me code, or tell me whence I can ftp it 
  408. (yes this usage of whence is correct) I'll obviously be able to get going 
  409. faster. Along the same lines, anyone know where I can get AVI source, or 
  410. the AVI specs so I can add AVI support?
  411.  
  412. UPDATE FOR 2.1
  413.  
  414. The connection between threads is now based on a message queue associated 
  415. with each thread. When a message is passed to a thread it is enqueued. 
  416. If a thread is busy (ie playing or saving to some format) and asks for 
  417. messages when there are none it is given a NULL message which it uses to 
  418. perform idle processing, otherwise it is put to sleep. Obviously this 
  419. mechanism looks very like the Process Manager's behavior. 
  420. Two consequences emerge from this.
  421. The first is that I can now, in the main event loop, peek for events and 
  422. if there are no events in my main event queue, return immediately. This 
  423. allows me to avoid the overhead of (very expensive) main event loop while 
  424. maintaining high interactivity. The cost of high interactivity is thus 
  425. reduced from about 12% of play time to about 1%.
  426. The second is that it makes it much easier to glue the user interface to a 
  427. different MPEG encoder or decoder (eg dedicated hardware) because the 
  428. connection between the user interface and the threads doing the work is 
  429. asynchronous.
  430. ================================================================================
  431.  
  432. ABOUT THE RESOURCES.
  433.  
  434. The default for the flags for all resources is purgable. 
  435. However there are some exceptions.
  436. • DLOGs and DITLs that will be opened by the TCL needed to be set nonpurgable
  437.     because of a bug in the TCL. I have altered CDLOGDialog to fix this and
  438.     these resources can now be purgable.
  439. • The DLOGs and DITLs used by CustomGetFile() and CustomPutFile() appear to 
  440.     need to be non-purgable even though IM says they can be purgable. If they 
  441.     are set    purgable the MemHell INIT registers errors during CustomGetFile() 
  442.     and CustomPutFile().
  443. • Menus may not be purgable because the menu manager does not allow that. 
  444.     Given this, one might as well make them preload and locked.
  445.     Likewise for the MBAR.
  446. • The DaTa resources, used to construct decoding tables, are mostly preload 
  447.     locked and treated just liked const global data. However there are a few 
  448.     small tables for which it is advantageous to load these into genuine global
  449.     arrays. For that case, the resources are marked purgable.
  450. • Marking resources Protected does not ever seem to be useful.
  451.  
  452. • If a dialog/alert makes uses of an ictb to change the font of text items, 
  453.     the associated dctb or actb must also be present or else nothing will 
  454.     happen.
  455. • Note that some of the dctb/itcb resources may appear redundant. However they 
  456.     prove to be necessary in unexpected ways. For example if they are not 
  457.     present for the CustomPutFile() DLOG, the dialog box drawn on screen will 
  458.     use dotted grey pattern to draw the items in the scrolling list of files,
  459.     rather than using a nice grey color. 
  460. ================================================================================
  461.  
  462. TIMING FOR WAITNEXTEVENT() AND FRIENDS
  463.  
  464. I wrote a simple loop that timed 200 passes each of these calls, and 
  465. recorded the times. For my outer loop over events, I want to know the cheapest 
  466. way of ascertaining whether I should get an event or not:
  467. For the last item, we timed 200 loops over the TCL core event routine,
  468. CApplication::Process1Event(), with nothing happening.
  469.  
  470. Time (in ticks) for 200 passes of:
  471.     EventAvail()           30
  472.     GetNextEvent          62
  473.     WaitNextEvent0          93        (WNE with mouseRegion==NULL and sleep==0)
  474.     WaitNextEvent1         493        (WNE with mouseRegion==NULL and sleep==1)
  475.     Loops over TCL Idle 1027
  476. ================================================================================
  477.  
  478. ACCURATE TIMINGS FOR SPARKLE.
  479.  
  480. These are timings taken for Sparkle 2.1 on my Q610 with 24bit color. The idea was
  481. to accurately time what were the hot spots in MPEG playback.
  482. All times reported are in ticks (60th of a second) and reflect the second time 
  483. the operation was performed. Very consistently it was found that the first time 
  484. an operation was performed took 11 ticks longer than subsequent times, presumably
  485. reflecting loading in purgable resources and such initialization.
  486.  
  487. Times to play Erika1.mpg. All times reflect playback time for 40 frames.
  488. The first time is split into times with debugger and without. 
  489. Once the program never calls WNE the debugger time becomes the same as the app time.
  490.  
  491. Standard parameters, thread time quantum=20 ticks, 
  492.   delay before yielding to other apps via WNE was infinity
  493.     When debugging time was         433 ticks         5.5 fps
  494.     As an application               402 ticks        6.0 fps
  495.     
  496. If we set an infinite yield time    
  497.                                     399 ticks        6.0 fps
  498. // All subsequent times use an infinite yield time.
  499. If we don't use a progress proc     
  500.                                     370 ticks
  501.  
  502. If we use a progress proc but it doesn't update the screen
  503.                                     373 ticks
  504.                 
  505. If we update the screen but don't use a movieController
  506.                                     332 ticks
  507.  
  508. //All subsequent times use an infinite yield time and no movie controller.
  509. If we omit YUV to RGB conversion
  510.                                     225 ticks
  511.                                     
  512. If we use only a DC term IDCT                                     
  513.                                     229 ticks
  514.  
  515. If we don't even call IDCT
  516.                                     226 ticks
  517.  
  518. If we don't call ReconstructIBlock()
  519.                                     295 ticks
  520.                                     
  521. If we use a 4x4 pseudo IDCT (very rough---can be written to be faster)
  522.                                     320 ticks
  523.  
  524. If we use QUALITY_STANDARD not QUALITY_HIGH
  525.                                     324 ticks
  526.                                     
  527. If we use QUALITY_LOW not QUALITY_HIGH
  528.                                     294 ticks
  529.  
  530.                                     
  531. From this we conclude that for 40 frames:
  532. WNE/thread yield overhead=3 to 4 ticks in an app, but about 35 ticks when debugging.
  533.     (This is nice---it means my scheme for drastically cutting WNE time works!)
  534. Progress proc function call overhead= 3 ticks.
  535.  
  536. CopyBits to 24bit screen= 25 ticks
  537. MovieController overhead= 40 ticks
  538. YUV to RGB                 =105 ticks
  539. IDCT                    =100 ticks
  540. Reconstruct I blocks    = 30 ticks (does cropping of the results)
  541. So Huffman                = 95 ticks
  542.  
  543. From these results we can expect to shave 15 ticks off the IDCT by using 4x4.
  544. We can shave off 30 ticks by using QUALITY_LOW.
  545. We can probably cut YUV to RGB in two or more by using the upper 5 bits of each 
  546. of YUV into a table.
  547.  
  548.  
  549. Some further results are:
  550.  
  551. Suppose we simply run the movie controller/text track and don't ever call 
  552. the MPEG code. This takes about 55 ticks.
  553. Suppose we hide the movie controller:    422 ticks (cf 433 ticks)
  554.                     text track        :    418 ticks
  555.                     both            :    408 ticks
  556.  
  557. The above timings largely correlate with the 2.1 code but fail to reflect 
  558. a few changes I've made since they were taken. Sometime I'll update them 
  559. again.
  560. -------------------------------------------------------------------------------
  561.  
  562. ABOUT THE MPEG ENCODING ALGORITHMS
  563.  
  564. Here is a little info about the MPEG encoding algorithms. 
  565.  
  566. First the P-search algorithms.
  567. In these algorithms, we have a given macroblock (a 16x16 block of pixels) and we 
  568. wish to search the previous frame to find the best match to this macroblock.
  569.  
  570. Logarithmic search works by dividing a search range ( a given area of pixels, say 
  571. 20x20 in size) into nine squares, selecting the center of each square, and testing 
  572. how well the area around that center matches the current macroblock. The area of the 
  573. center that matches best is itself divided into nine and so on until one can go no 
  574. further. This is a very fast search technique. Without halfpixels enabled, it takes 
  575. 25 compares per macroblocks. With halfpixels enabled, it takes 33 searches per 
  576. macroblock. Thus halfpixels are not much more expensive, and substantially lower
  577. the size of the resultant file (by 5 to 10%).
  578.  
  579. Two level search works by searching all the possible displacements in the search
  580. range that are (even if halfpixels are enabled) or (a multiple of four if 
  581. halfpixels are not enabled). The site with the best match is then tested at 
  582. all the eight sites around it and the best of the nine chosen.
  583. This takes 108 searches per macroblock without halfpixels, and 408 if halfpixels are 
  584. enabled.
  585.  
  586. Exhaustive search searches every acceptable motion in the search range to find the 
  587. best match. It takes 400 searches without halfpixels on, and 1600 with half pixels
  588. on.
  589.  
  590. Now the B algorithms.
  591. All of these algorithms use as their starting point whatever P-algorithm you have
  592. chosen and work with that as a basic block.
  593.  
  594. The simple algorithm does two P-searches, searching the current macroblock against
  595. the past picture and against the future picture. The best past motion vector and 
  596. the best forward motion vector are used to calculate the interpolating frame,
  597. and the best of forward, backward and interpolating motion is calculated.
  598.  
  599. Cross2 does four P-searches. The first two proceed as in Simple search. Then, using 
  600. the forward motion vector from the simple search, a P-search is made of the future 
  601. picture to find the best interpolation forward vector. Likewise using the forward 
  602. vector from the simple search, a P-search is made of the past picture to find the 
  603. best interpolation backward vector. The best match of all four searches is used.
  604.  
  605. Finally exhaustive search performs a wopping 400 P-searches per macroblock, 1600
  606. if half-pixels are on. Each of those searches uses the current forward motion vector
  607. to search for a best interpolating backward motion vector.
  608.  
  609. -------------------------------------------------------------------------------
  610.